package com.itheima.service.front.impl;

import com.itheima.dao.front.ExamPaperDao;
import com.itheima.dao.front.ExamQuestionDao;
import com.itheima.dao.store.QuestionDao;
import com.itheima.domain.front.ExamPaper;
import com.itheima.domain.front.ExamQuestion;
import com.itheima.domain.store.Question;
import com.itheima.factory.MapperFactory;
import com.itheima.service.front.ExamQuestionService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: mm_exam_review
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-16 14:37
 **/
public class ExamQuestionServiceImpl implements ExamQuestionService {
    @Override
    public List<Question> getPaper() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao examQuestionDao = MapperFactory.getMapper(
                    sqlSession, QuestionDao.class);
            return examQuestionDao.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public boolean applyPaper(String memberId, List<ExamQuestion> examQuestionList) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            boolean flag = true;
            //2.获取Dao
            ExamPaperDao examPaperDao = MapperFactory.getMapper(sqlSession,
                    ExamPaperDao.class);
            ExamQuestionDao examQuestionDao =
                    MapperFactory.getMapper(sqlSession, ExamQuestionDao.class);
//3.提交保存的试卷信息
            ExamPaper examPaper = new ExamPaper();
            String paperId = UUID.randomUUID().toString();
            examPaper.setId(paperId);
            examPaper.setApplyTime(new Date());
            examPaper.setMemberId(memberId);
            examPaper.setState("1");
            flag = flag && examPaperDao.save(examPaper) > 0;
//4.提交保存的试卷中的所有题目对应的答案信息
            for (ExamQuestion eq : examQuestionList) {
                eq.setId(UUID.randomUUID().toString());
                eq.setExamPaperId(paperId);
                flag = flag && examQuestionDao.save(eq) > 0;
            }
            TransactionUtil.commit(sqlSession);
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
